package com.biz.controller.weixin;

import com.biz.model.Pmodel.weixin.OAuthAccessToken;
import com.biz.service.weixin.WXUtilService;
import com.biz.utils.ConfigUtil;
import com.framework.util.weixin.WechatAccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

@Controller
public class OAuth2Controller {

	@Resource(name="wxUtilService")
	private WXUtilService wxUtilService;

	/**
	 * 构造参数并将请求重定向到微信API获取登录信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = { "/wx_oauth2"})
	public String Oauth2API(HttpServletRequest request,
							String resultUrl) throws Exception{
		// 此处可以添加获取持久化的数据，如企业号id等相关信息
		System.out.println("进入wx_oauth2");
		String redirectUrl = "";
		String appId = ConfigUtil.get("appId");
		if (resultUrl != null) {
			System.out.println("进入方法");
			String backUrl = ConfigUtil.get("SYS_URL") + "/wx_oauth2url.ac?oauth2url="
					+ resultUrl;
			redirectUrl = oAuth2Url(appId,backUrl);
		}
		System.out.println("redirectUrl:"+redirectUrl);
		return "redirect:" + redirectUrl;
	}

	/**
	 * 根据code获取Userid后跳转到需要带用户信息的最终页面
	 *
	 * @param request
	 * @param code
	 *            获取微信重定向到自己设置的URL中code参数
	 * @param oauth2url
	 *            跳转到最终页面的地址
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/wx_oauth2url" })
	public String Oauth2MeUrl(HttpServletRequest request,
							  @RequestParam String code,
							  @RequestParam String oauth2url)
			throws Exception {
		System.err.println("进入wx_oauth2url");
		String appId =ConfigUtil.get("appId");
		String appSecret =ConfigUtil.get("appSecret");

		OAuthAccessToken accessToken = WechatAccessToken.getAccessToken(
				appId,appSecret, code);
		request.getSession().invalidate();
		HttpSession session = request.getSession(true);
		if (accessToken != null) {
			System.out.println("Openid:" + accessToken.getOpenid());
			System.out.println("access_token:" + accessToken.getToken());
			session.setAttribute(ConfigUtil.get("SESSION_OPEN_ID"), accessToken.getOpenid());
		}
		return "redirect:" + oauth2url;
	}

	/**
	 * 构造带员工身份信息的URL
	 *
	 *            企业id
	 * @param redirect_uri
	 *            授权后重定向的回调链接地址，请使用urlencode对链接进行处理
	 * @param
	 *
	 * @return
	 */
	private String oAuth2Url(String corpid, String redirect_uri) {
		try
		{
			redirect_uri = java.net.URLEncoder.encode(redirect_uri, "utf-8");
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ corpid
				+ "&redirect_uri="
				+ redirect_uri
				+ "&response_type=code&scope=snsapi_base&state=ok#wechat_redirect";
		return oauth2Url;
	}


}
